package com.motu.vertx.module.utility.toolset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 时间工具类（时间戳定义为long类型时使用此类，int类型的时间戳只能支持到2038-01-01）
 */
public class TimeUtils {

    public static final Logger logger = LoggerFactory.getLogger("TimeUtils");

    public static final int MS = 1000;// 1秒=1000毫秒
    public static final int MINUTE = 60;// 分
    public static final int HOUR = 60 * MINUTE;// 小时
    public static final int DAY = 24 * HOUR;// 天
    public static final int WEEK = 7 * DAY;// 周

    /**
     * 获取当前时间
     * @return 当前时间 秒数
     */
    public static long getCurTime() {
        long curTime = System.currentTimeMillis() / MS;
        return curTime;
    }

    /**
     * 判断某个时间的日期是不是在今天
     * @param rtime 时间值
     * @return true表示是今天，false反之
     */
    public static boolean isToday(long rtime) {
        long tt = rtime * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        Date curdate = new Date();
        cal.setTime(curdate);
        int curyear = cal.get(Calendar.YEAR);
        int curmonth = (cal.get(Calendar.MONTH)) + 1;
        int curday = cal.get(Calendar.DAY_OF_MONTH);
        return year == curyear && month == curmonth && day == curday;
    }

    /***
     * 是否在今日X时内
     * @param hour 小时
     * @param rtime 目标时间
     */
    public static boolean isToday(long rtime, int hour) {
        long curTime = getCurTime();
        long diffTime = dayDifftime(hour + ":00:00");
        long startTime = 0;
        long endTime = 0;
        if (diffTime == 0) {
            startTime = curTime;
            endTime = curTime + DAY;
        } else {
            startTime = curTime + diffTime - DAY;
            endTime = curTime + diffTime;
        }
        return rtime >= startTime && rtime < endTime;
    }

    /***
     * 查询当前时间到指定的时间的时间差（每天）
     * @param hhmmss 指定的时间（HH:mm:ss格式）
     * @return 时间差（秒）
     */
    public static long dayDifftime(String hhmmss) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String strToday = df.format(new Date());
            String strTarget = strToday + " " + hhmmss;// 目标时间
            df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            strToday = df.format(new Date());// 当前时间
            Date target = df.parse(strTarget);
            Date today = df.parse(strToday);
            long diff = target.getTime() - today.getTime();
            if (diff < 0) {
                diff += DAY * MS;
            }
            return diff / MS;
        } catch (Exception e) {
            logger.error("dayDifftime error : " + Tool.getException(e));
            return -1;
        }
    }

	/***
	 * 查询当前时间到指定的时间的时间差（每天）
	 * @param hhmmss 指定的时间（HH:mm:ss格式）
	 * @param offset 偏移量（秒），偏移量要参与计算，否则会导致隔天的时间差计算错误
	 * @return 时间差（秒）
	 */
	public static long dayDifftime(String hhmmss, int offset) {
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String strToday = df.format(new Date());
			String strTarget = strToday + " " + hhmmss;// 目标时间
			df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			strToday = df.format(new Date());// 当前时间
			Date target = df.parse(strTarget);
			Date today = df.parse(strToday);
			long diff = target.getTime() + (offset * MS) - today.getTime();
			if (diff < 0) {
				diff += DAY * MS;
			}
			return diff / MS;
		} catch (Exception e) {
			logger.error("dayDifftime error : " + Tool.getException(e));
			return -1;
		}
	}

    /***
     * 是否在今日指定时间内
     * @param rtime 目标时间
     * @param hhmmss 时分秒
     */
    public static boolean isToday(long rtime, String hhmmss) {
        long curTime = getCurTime();
        long diffTime = dayDifftime(hhmmss);
        long startTime = 0;
        long endTime = 0;
        if (diffTime == 0) {
            startTime = curTime;
            endTime = curTime + DAY;
        } else {
            startTime = curTime + diffTime - DAY;
            endTime = curTime + diffTime;
        }
        return rtime >= startTime && rtime < endTime;
    }

    /***
     * 指定时间和当前时间是否是同一个月
     * @param rtime 指定时间
     * @return 是否同一个月
     */
    public static boolean isSameMonth(long rtime) {
        long tt = rtime * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        Date curdate = new Date();
        cal.setTime(curdate);
        int curyear = cal.get(Calendar.YEAR);
        int curmonth = (cal.get(Calendar.MONTH)) + 1;
        return year == curyear && month == curmonth;
    }

    /***
     * 判断两个时间点是否是同一天
     * @param time1 时间1
     * @param time2 时间2
     * @return 是否是同一天
     */
    public static boolean isOneDay(long time1, long time2) {
        long tt1 = time1 * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt1);
        int year1 = cal.get(Calendar.YEAR);
        int month1 = (cal.get(Calendar.MONTH)) + 1;
        int day1 = cal.get(Calendar.DAY_OF_MONTH);
        long tt2 = time2 * MS;
        cal.setTimeInMillis(tt2);
        int year2 = cal.get(Calendar.YEAR);
        int month2 = (cal.get(Calendar.MONTH)) + 1;
        int day2 = cal.get(Calendar.DAY_OF_MONTH);
        return year1 == year2 && month1 == month2 && day1 == day2;
    }

    /***
     * 获取跟某一个时间戳同一天内的指定时间
     * @param rtime 时间戳
     * @param hour 小时
     * @param minute 分
     * @param second 秒
     * @return 新的时间戳
     */
    public static long getTimeStrIntValue2(long rtime, int hour, int minute, int second) {
        long tt = rtime * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH));
        int day = cal.get(Calendar.DAY_OF_MONTH);
        Calendar cd1 = Calendar.getInstance();
        cd1.set(year, month, day, hour, minute, second);
        Date d1 = cd1.getTime();
        return d1.getTime() / MS;
    }

    /***
     * 判断一时间戳是否是昨天
     * @param rtime
     * @return 判断结果
     */
    public static boolean isYesterday(long rtime) {
        long tmp = rtime + DAY;
        return isToday(tmp);
    }

    /**
     * 判断当前时间是不是在某个设定时间内 比如[20：30，21：00）
     * @param startHour 起始小时
     * @param startMin 起始分钟
     * @param endHour 结束小时
     * @param endMin 结束分钟
     * @return true表示是，false反之
     */
    public static boolean checkTime(int startHour, int startMin, int endHour, int endMin) {
        Calendar cd = Calendar.getInstance();// 取得Calendar实例
        int year = cd.get(Calendar.YEAR);
        int month = (cd.get(Calendar.MONTH));
        int day = cd.get(Calendar.DAY_OF_MONTH);
        Calendar cd1 = Calendar.getInstance();
        Calendar cd2 = Calendar.getInstance();
        cd1.set(year, month, day, startHour, startMin, 0);
        cd2.set(year, month, day, endHour, endMin, 0);
        Date d = cd.getTime();// 取得当前时间
        Date d1 = cd1.getTime();
        Date d2 = cd2.getTime();
        int a1 = d.compareTo(d1);
        int a2 = d.compareTo(d2);
        return a1 >= 0 && a2 < 0;// 在这个时间范围内
    }

    /***
     *  获取当天指定小时分秒的时间戳
     * @param hour 小时
     * @param minute 分
     * @param second 秒
     * @return 时间戳
     */
    public static long getTimeIntValue(int hour, int minute, int second) {
        Calendar cd = Calendar.getInstance();// 取得Calendar实例
        int year = cd.get(Calendar.YEAR);
        int month = (cd.get(Calendar.MONTH));
        int day = cd.get(Calendar.DAY_OF_MONTH);
        Calendar cd1 = Calendar.getInstance();
        cd1.set(year, month, day, hour, minute, second);
        Date d1 = cd1.getTime();
        return d1.getTime() / MS;
    }

    /**
     * 将时间转成字符串型
     * @param time 时间值
     * @return 转换后的时间值格式：2000-05-02 18:56
     */
    public static String getTimeStr(long time) {
        long tt = time * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        String str = String.format("%d-%02d-%02d %02d:%02d", year, month, day, hour, minute);
        return str;
    }

    /***
     * 根据时间戳获取日期字符串
     * @param time 时间戳
     * @return 字符串，如20170628
     */
    public static String getDayStr(long time) {
        long tt = time * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String str = String.format("%d%02d%02d", year, month, day);
        return str;
    }

    /***
     * 根据时间戳获取年月字符串
     * @param time 时间戳
     * @return 字符串，如201706
     */
    public static String getMonthStr(long time) {
        long tt = time * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        String str = String.format("%d%02d", year, month);
        return str;
    }

    /***
     * 将时间戳转换成字符串
     * @param time 时间戳
     * @return 转换结果，如2017-06-28 14:42:08
     */
    public static String getTimeFullStr(long time) {
        long tt = time * MS;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        String str = String.format("%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second);
        return str;
    }

    /***
     * 将时间戳转换成字符串 精确到毫秒
     * @param millisecond 时间戳（毫秒）
     * @return 转换结果，如2021-06-30 16:55:40.292
     */
    public static String getMsTimeFullStr(long millisecond){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String d = format.format(millisecond);
        return d;
    }

    /***
     * 将字符串格式的时间转换成时间戳
     * @param str 时间字符串，如2017-06-28 14:42:08
     * @return 时间戳
     */
    public static long getTimeStrIntValue(String str) {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format1.parse(str);
            return date.getTime() / MS;
        } catch (ParseException e) {
            logger.error("getTimeStrIntValue error : " + Tool.getException(e));
        }
        return 0;
    }

    /**
     * 将时间戳转成日期字符串型
     * @param millisecond 时间值（毫秒）
     * @return 转换后的时间值格式：2000-05-02
     */
    public static String getDateStr(long millisecond) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millisecond);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String str = String.format("%d-%02d-%02d", year, month, day);
        return str;
    }

    /**
     * 计算某个时间值到当前已经过了多久
     * @param startTime 起始时间
     * @return 时间差秒数
     */
    public static long getTimeDiff(long startTime) {
        long curTime = System.currentTimeMillis() / MS;
        return curTime - startTime;
    }
    /***
     * 计算cd时间还有多久
     * @param startTime 上次执行时间
     * @param maxTime cd总时长
     * @return 0表示没有cd了，>0表示还有cd时间（秒）
     */
    public static long getTimeLeft(long startTime, long maxTime) {
        long diff = getTimeDiff(startTime);
        long left = Math.max(0, maxTime - diff);
        return left;
    }

    /**
     * 根据指定时间获得下周的某一时间
     * @param time 指定时间
     * @param target 某一天（0\1\2\3\4\5\6)周日至周六
     * @return 下周某一天日期
     */
    public static long getNextDayOfWeek(long time, int target) {
        long stime = getStartTimeOfDay(time);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(stime * MS);
        //距离下周日的天数 (星期日,星期一,...,星期六)
        int[] adddays = {7,6,5,4,3,2,1};
        //以星期日作为一周的开始
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) -1;
        //时装周第一批开启的时间 (开服时间的下一周 周日 开启时装周活动)
        long nextWeekStime = stime + adddays[dayOfWeek] * DAY;
        nextWeekStime += target * DAY;
        return nextWeekStime;
    }

    /***
     * 根据传入的时间取得这个时间当日的起始时间值
     * @param time
     * @return 当日的起始时间值
     */
    public static long getStartTimeOfDay(long time) {
        long tt = time * MS;

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);

        String str = String.format("%d-%02d-%02d 00:00:00", year, month, day);
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format1.parse(str);
            return date.getTime() / MS;
        } catch (Exception e) {
            logger.error("getStartTimeOfDay error : " + Tool.getException(e));
        }
        return 0;
    }

    /**
     * 获得今天是本周的第几天
     * @return （0\1\2\3\4\5\6)周日至周六
     */
    public static int getDayOfWeek() {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日1，星期一是2，星期六是7......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek - 1;
    }

    /**
     * 获得指定时间是周几
     *
     * @return （0\1\2\3\4\5\6)周日至周六
     */
    public static int getTimeOfWeek(long time) {
        long tt = time * MS;

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        // 获得指定时间是一周的第几天，星期日1，星期一是2，星期六是7......
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek - 1;
    }

    /***
     * 获得本周未来某一天的日期（yyyy-MM-dd） -- 取不到过去时间 !!!
     * @param target 某一天（0\1\2\3\4\5\6)周日至周六
     * @return 本周某一天日期（如果超过则取下周的时间）
     */
    public static String getWeekOneDay(int target) {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日1，星期一是2，星期六是7......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
        int plus = target - dayOfWeek;// 计算相差几天 (dayOfWeek = 3 target = 4) or (dayOfWeek = 4 target = 3)
        if (plus < 0) {
            plus += 7;
        }

        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, plus);
        Date day = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strDay = df.format(day);
        return strDay;
    }

    /***
     * 获得本周指定某一天的日期（yyyy-MM-dd）-- (周一到周日算一周)
     * @param target 某一天（1\2\3\4\5\6\7)周一至周日
     * @return 本周某一天日期
     */
    public static String getWeekOneDayOfTarget(int target) {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日1，星期一是2，星期六是7......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
        dayOfWeek = dayOfWeek == 0 ? dayOfWeek + 7 :dayOfWeek;
        int plus = target - dayOfWeek;// 计算相差几天 (dayOfWeek = 3 target = 4) or (dayOfWeek = 4 target = 3)

        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, plus);
        Date day = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strDay = df.format(day);
        return strDay;
    }

    /***
     * 获得本周某一天时间戳
     * @param target 某一天（0\1\2\3\4\5\6)周日至周六
     * @param hour 小时
     * @return 本周某一天时间戳
     */
    public static long getWeekOneTime(int target, int hour) {
        if (target == 0) {
            target = 7;// 周日
        }
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日1，星期一是2，星期六是7......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek == 0) {
            dayOfWeek = 7;// 周日
        }
        int plus = target - dayOfWeek;// 计算相差几天 (dayOfWeek = 3 target = 4) or (dayOfWeek = 4 target = 3)
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, plus);
        Date day = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strDay = df.format(day);
        try {
            df = new SimpleDateFormat("yyyy-MM-dd HH");
            Date date = df.parse(strDay + " " + hour);
            return date.getTime() / MS;
        } catch (Exception e) {
            logger.error("getWeekOneTime error : " + Tool.getException(e));
            return -1;
        }
    }

    /***
     * 获得本周某一天时间戳
     * @param target 某一天（0\1\2\3\4\5\6)周日至周六
     * @param time HH:mm:ss
     * @return 本周某一天时间戳
     */
    public static long getWeekOneTime(int target, String time) {
        if (target == 0) {
            target = 7;// 周日
        }
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日1，星期一是2，星期六是7......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek == 0) {
            dayOfWeek = 7;// 周日
        }
        int plus = target - dayOfWeek;// 计算相差几天 (dayOfWeek = 3 target = 4) or (dayOfWeek = 4 target = 3)
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, plus);
        Date day = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strDay = df.format(day);
        try {
            df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = df.parse(strDay + " " + time);
            return date.getTime() / 1000;
        } catch (Exception e) {
            logger.error("getWeekOneTime error : " + Tool.getException(e));
            return -1;
        }
    }


    /***
     * 获得本周某一天时间戳(周日为第一天，周六最后一天)
     * @param target 某一天（0\1\2\3\4\5\6)周日至周六
     * @param time HH:mm:ss
     * @return 本周某一天时间戳
     */
    public static long getWeekOneTimeStartSunday(int target, String time) {
        if (target == 7){
            target = 0;
        }
        target++;
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日1，星期一是2，星期六是7......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
        int plus = target - dayOfWeek;// 计算相差几天 (dayOfWeek = 3 target = 4) or (dayOfWeek = 4 target = 3)
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, plus);
        Date day = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strDay = df.format(day);
        try {
            df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = df.parse(strDay + " " + time);
            return date.getTime() / MS;
        } catch (Exception e) {
            logger.error("getWeekOneTimeStartSunday error : " + Tool.getException(e));
            return -1;
        }
    }

    /***
     * 查询当前时间到指定的时间的时间差（每周）
     * @param yyyymmdd 指定的日期
     * @param hhmmss 指定的时间（HH:mm:ss格式）
     * @return 时间差（秒）
     * @throws Exception
     */
    public static long weekDifftime(String yyyymmdd, String hhmmss) {
        String strTarget = yyyymmdd + " " + hhmmss;// 目标时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strToday = df.format(new Date());// 当前时间
        try {
            Date target = df.parse(strTarget);
            Date today = df.parse(strToday);
            long diff = target.getTime() - today.getTime();
            if (diff < 0) {
                diff += WEEK * MS;
            }
            return diff / 1000;
        } catch (Exception e) {
            logger.error("weekDifftime error : " + Tool.getException(e));
            return -1;
        }
    }

	/***
	 * 查询当前时间到指定的时间的时间差（每周）
	 * @param yyyymmdd 指定的日期
	 * @param hhmmss 指定的时间（HH:mm:ss格式）
	 * @param offset 偏移量（秒），偏移量要参与计算，否则会导致隔周的时间差计算错误
	 * @return 时间差（秒）
	 * @throws Exception
	 */
	public static long weekDifftime(String yyyymmdd, String hhmmss, int offset) {
		String strTarget = yyyymmdd + " " + hhmmss;// 目标时间
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String strToday = df.format(new Date());// 当前时间
		try {
			Date target = df.parse(strTarget);
			Date today = df.parse(strToday);
			long diff = target.getTime() + (offset * MS) - today.getTime();
			if (diff < 0) {
				diff += WEEK * MS;
			}
			return diff / 1000;
		} catch (Exception e) {
			logger.error("weekDifftime error : " + Tool.getException(e));
			return -1;
		}
	}

    /**
     * 获取今天某个时间戳
     */
    public static long getTodayOneTime(String hhmmss) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String strToday = df.format(new Date());
            String strTarget = strToday + " " + hhmmss;// 目标时间
            df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date target = df.parse(strTarget);
            return target.getTime() / MS;
        } catch (ParseException e) {
            logger.error("getTodayOneTime error : " + Tool.getException(e));
        }
        return 0;
    }

    /***
     * 计算目标时间到当前时间相差几天（例如今天是2013-05-22，目标时间是2013-05-21，那么相差1天）
     * @param time 目标时间
     * @return 相差几天
     */
    public static int getDiffDay(long time) {
        int diffDay = 0;// 相差天数
        long curTime = getCurTime();// 当前时间
        if (curTime == time) {
            return diffDay;
        } else if (curTime > time) {
            diffDay = (int)((curTime - time) / DAY);
            int mod = (int)((curTime - time) % DAY);
            if (mod != 0 && !isOneDay(curTime, time + diffDay * DAY)) {
                diffDay++;
            }
        } else {
            diffDay = (int)((time - curTime) / DAY);
            int mod = (int)((time - curTime) % DAY);
            if (mod != 0 && !isOneDay(curTime, time - diffDay * DAY)) {
                diffDay++;
            }
        }
        return diffDay;
    }

    /***
     * 计算两个时间相差几天（例如时间1是2013-05-22，时间2是2013-05-21，那么相差1天）
     * @param time1 时间1
     * @param time2 时间2
     * @return 相差几天
     */
    public static int getDiffDay(long time1, long time2) {
        int diffDay = 0;// 相差天数
        if (isOneDay(time1, time2)) {
            return diffDay;
        } else if (time2 > time1) {
            diffDay = (int)((time2 - time1) / DAY);
            int mod = (int)((time2 - time1) % DAY);
            if (mod != 0 && !isOneDay(time2, time1 + diffDay * DAY)) {
                diffDay++;
            }
        } else {
            diffDay = (int)((time1 - time2) / DAY);
            int mod = (int)((time1 - time2) % DAY);
            if (mod != 0 && !isOneDay(time2, time1 - diffDay * DAY)) {
                diffDay++;
            }
        }
        return diffDay;
    }

    /***
     * 计算两个时间相差月数（例如时间1是2020-01-01，时间2是2013-02-11，那么相差1个月）
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 间隔月数
     */
    public static int getIntervalMonth(String startTime,String endTime) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar startdate = Calendar.getInstance();
        Calendar enddate = Calendar.getInstance();
        try {
            startdate.setTime(format.parse(startTime));
            enddate.setTime(format.parse(endTime));
            return (enddate.get(Calendar.YEAR) - startdate.get(Calendar.YEAR)) * 12  + enddate.get(Calendar.MONTH) - startdate.get(Calendar.MONTH) ;
        } catch (Exception e) {
            logger.error("getIntervalMonth error : " + Tool.getException(e));
        }
        return 0;
    }

    /***
     * 指定时间和当前时间是否是同一周(周一到周日算一周)
     * @param time1 指定时间
     * @param time2 指定时间
     * @return 是否同一周
     */
    public static boolean isSameWeek(long time1, long time2) {
        String date1 = getTimeStr(time1);
        String date2 = getTimeStr(time2);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = format.parse(date1);
            d2 = format.parse(date2);
        } catch (Exception e) {
            logger.error("isSameWeek error : " + Tool.getException(e));
        }
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setFirstDayOfWeek(Calendar.MONDAY);
        cal2.setFirstDayOfWeek(Calendar.MONDAY);
        cal1.setTime(d1);
        cal2.setTime(d2);
        int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
        // subYear==0,说明是同一年
        if (subYear == 0) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        // 例子:cal1是"2005-1-1"，cal2是"2004-12-25"
        // java对"2004-12-25"处理成第52周
        // "2004-12-26"它处理成了第1周，和"2005-1-1"相同了
        // 大家可以查一下自己的日历
        // 处理的比较好
        // 说明:java的一月用"0"标识，那么12月用"11"
        else if (subYear == 1 && cal2.get(Calendar.MONTH) == 11) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        // 例子:cal1是"2004-12-31"，cal2是"2005-1-1"
        else if (subYear == -1 && cal1.get(Calendar.MONTH) == 11) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;

        }
        return false;
    }

    /***
     * 指定时间和当前时间是否是同一周(周日到周六算一周)
     * @param time1 指定时间
     * @param time2 指定时间
     * @return 是否同一周
     */
    public static boolean isSameWeekSunday(long time1, long time2) {
        String date1 = getTimeStr(time1);
        String date2 = getTimeStr(time2);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = format.parse(date1);
            d2 = format.parse(date2);
        } catch (Exception e) {
            logger.error("isSameWeekSunday error : " + Tool.getException(e));
        }
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setFirstDayOfWeek(Calendar.SUNDAY);
        cal2.setFirstDayOfWeek(Calendar.SUNDAY);
        cal1.setTime(d1);
        cal2.setTime(d2);
        int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
        // subYear==0,说明是同一年
        if (subYear == 0) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        // 例子:cal1是"2005-1-1"，cal2是"2004-12-25"
        // java对"2004-12-25"处理成第52周
        // "2004-12-26"它处理成了第1周，和"2005-1-1"相同了
        // 大家可以查一下自己的日历
        // 处理的比较好
        // 说明:java的一月用"0"标识，那么12月用"11"
        else if (subYear == 1 && cal2.get(Calendar.MONTH) == 11) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        // 例子:cal1是"2004-12-31"，cal2是"2005-1-1"
        else if (subYear == -1 && cal1.get(Calendar.MONTH) == 11) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;

        }
        return false;
    }

    /***
     * 根据传入的时间取得这个时间当月的首日时间
     * @param time
     * @return 首日时间
     */
    public static long getFirstDayOfMonth(long time) {
        long tt = time * MS;

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 1;
        String str = String.format("%d-%02d-%02d 00:00:00", year, month, 1);
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format1.parse(str);
            return date.getTime() / MS;
        } catch (Exception e) {
            logger.error("getFirstDayOfMonth error : " + Tool.getException(e));
        }
        return 0;
    }

    /***
     * 根据传入的时间取得这个时间下个月第一秒
     * @param time
     * @return 下个月第一秒
     */
    public static long getLastTimeOfMonth(long time) {
        long tt = time * MS;

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(tt);
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH)) + 2;
        String str = String.format("%d-%02d-%02d 00:00:00", year, month, 1);
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format1.parse(str);
            return date.getTime() / MS;
        } catch (Exception e) {
            logger.error("getLastTimeOfMonth error : " + Tool.getException(e));
        }
        return 0;
    }

    /**
     * 非ISO标准的时间格式(例如 1:0:2 或 1:0)补齐为 HH:mm:ss 格式
     */
    public static String formatDayTimeString(String timeString) {
        String[] parts = timeString.replace(" ", "").split(":");
        // 确保小时、分钟和秒都至少有两位数
        return String.format("%02d:%02d:%02d",
                Integer.parseInt(parts[0]),
                Integer.parseInt(parts.length > 1 ? parts[1] : "0"),
                Integer.parseInt(parts.length > 2 ? parts[2] : "0"));
    }

}
